/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tri.gui.worker;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import org.tri.entity.Transaccion;
import org.tri.gui.worker.retrievers.DataRetriever;
import org.tri.model.TransaccionTableModel;

/**
 *
 * @author giaco
 */
public class TransaccionFillWorker<K> extends SwingWorker<List<K>, Object> {
    
    private TransaccionTableModel model;
    private DataRetriever<K> retriever;
    private List<TableFillListener> listenerList;

    public TransaccionFillWorker( TransaccionTableModel model, 
                            DataRetriever<K> retriever ) {
        super();
        this.model = model;
        this.retriever = retriever;
        
        listenerList = new ArrayList<TableFillListener>();

    }//end constructor

    public final void addTransaccionFillListener( TableFillListener listener ) {
        listenerList.add( listener );

    }//end método addTableFillListener

    public final void removeTransaccionFillListener( TableFillListener listener ) {
        listenerList.remove( listener );

    }//end método removeTableFillListener

    private void fireDoneFillingTable() {
        for ( TableFillListener listener : listenerList )
            listener.doneFillingTable();

    }//end métdoo fireDoneFillingTable

    private void fireErrorFillingTable( ExecutionException ex ) {
        for ( TableFillListener listener : listenerList )
            listener.errorFillingTable( ex );

    }//end método errorFillingTable

    @Override
    protected List<K> doInBackground() throws Exception {
        return retriever.retrieveData();
        
    }//end método doInBackground 
    
    @Override
    protected void done() {
        super.done();
        //realizamos las tareas en el thread de eventos
        SwingUtilities.invokeLater( new Runnable() {

            @Override
            public void run() {
                try {
                //asignamos las filas
                model.setFilas( getFilas() );
                
                }finally {
                    //enviamos el done a los listeners
                    fireDoneFillingTable();
                    
                }

            }//end método run

        } );

    }//end método done
    
    public List<Transaccion> getFilas(){
        ArrayList<Transaccion> filas = new ArrayList<Transaccion>();
        try {
            for(Object o : get()){
                filas.add( (Transaccion) o);
            }
        } catch ( InterruptedException ex ) {
        } catch ( ExecutionException ex ) {
                    //enviamos el error a los listeners
                    fireErrorFillingTable( ex );

        }
        return filas;
        
    }//end metodo getFilas

}//end clase TransaccionFillWorker

